package com.myc.cloud.gateway.config.limit;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import reactor.core.publisher.Mono;

/**
 * @Classname RateLimitConfig
 * @Description 限流配置
 * @Date 2020-08-24 12:41
 * @Created by myc
 */
@Configuration
public class RateLimitConfig {

    /**
     * api限流
     * @return
     */
    @Bean
    public KeyResolver apiKeyResolver() {
        System.out.println("限流解析器");
        return exchange -> Mono.just(exchange.getRequest().getPath().toString());
    }

    /**
     * 用户限流
     * @return
     */
    @Bean
    KeyResolver userKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("userId"));
    }

    /**
     * ip限流
     */
    @Bean
    @Primary
    public KeyResolver ipKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
    }
}
